package cn.wolfcode.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class AliOSSUtils {
    @Autowired
    private AlliOSSProperties alliOSSProperties;
    public String upload(MultipartFile file)throws Exception {
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString() + extName;
        OSS oss = new OSSClientBuilder().build(alliOSSProperties.getEndpoint(), alliOSSProperties.getAccessKeyId(), alliOSSProperties.getAccessKeySecret());
        oss.putObject(alliOSSProperties.getBucketName(), newFileName, inputStream);
        oss.shutdown();
        StringBuffer sb = new StringBuffer(alliOSSProperties.getEndpoint());
        StringBuffer url = sb.insert(8, alliOSSProperties.getBucketName() + "." ).append("/").append(newFileName);
        return url.toString();
    }
}
